<template>
  <div class="password-reset-container">
    <div v-if="step === 1" class="step">
      <h2>身份认证</h2>
      <form @submit.prevent="nextStep1">
        <label for="email">邮箱:</label>
        <input type="email" id="email" v-model="form1.email" required />
        <button type="button" @click="sendAuthCode" :disabled="isSendButtonDisabled">
          {{ countdown > 0 ? `${countdown}s后重发` : '获取验证码' }}
        </button>
        <p v-if="emailError" style="color: red;">{{ emailError }}</p>
        <label for="authCode">验证码:</label>
        <input type="text" id="authCode" v-model="form1.authCode" required />
        <p v-if="authCodeError" style="color: red;">验证码必须为6位有效数字.</p>
        <button type="submit" :disabled="!isFormValid">下一步</button>
      </form>
    </div>

    <div v-if="step === 2" class="step">
      <h2>重置密码</h2>
      <form @submit.prevent="nextStep2">
        <label for="password">新密码:</label>
        <input type="password" id="password" v-model="form2.password" required />
        <label for="confirmPassword">确认密码:</label>
        <input type="password" id="confirmPassword" v-model="form2.confirmPassword" required />
        <p v-if="passwordMismatch" style="color: red;">两次密码不匹配.</p>
        <button type="submit" :disabled="!isSecondStepFormValid">重置密码</button>
      </form>
    </div>

    <div v-if="step === 3" class="step">
      <h2>重置成功</h2>
      <p>你的密码重置成功!</p>
      <button @click="login">去登录</button>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import Swal from 'sweetalert2';

export default {
  data() {
    return {
      step: 1,
      form1: {
        email: '',
        authCode: '',
      },
      form2: {
        password: '',
        confirmPassword: '',
      },
      countdown: 0,
      emailError: '',
      authCodeError: '',
      passwordMismatch: false,
      loading: false,
    };
  },
  computed: {
    isSecondStepFormValid() {
      return this.form2.password === this.form2.confirmPassword;
    },
    isSendButtonDisabled() {
      return this.countdown > 0;
    },
    isFormValid() {
      return this.form1.email && this.form1.authCode.length === 6;
    },
  },
  methods: {
    validateEmail() {
      const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailPattern.test(this.form1.email)) {
        this.emailError = '请输入一个合法的邮箱地址';
        return false;
      }
      this.emailError = '';
      return true;
    },
    async sendAuthCode() {
      if (!this.validateEmail()) {
        this.authCodeError = 'Please enter a valid email address';
        return;
      }
      this.loading = true;
      try {
        const response = await axios.post('http://8.219.49.219:8080/onlineShopping/user/sendEmail', {
          email: this.form1.email,
        }, {
          withCredentials: true,
        });
        this.startCountdown();
        console.log(response);
      } catch (error) {
        let errorMessage = 'Failed to send verification code.';
        if (error.response && error.response.data && error.response.data.message) {
          errorMessage = error.response.data.message;
        }
        Swal.fire({
          icon: 'error',
          title: 'Error',
          text: errorMessage,
        });
      } finally {
        this.loading = false;
      }
    },
    startCountdown() {
      this.countdown = 60;
      const interval = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--;
        } else {
          clearInterval(interval);
        }
      }, 1000);
    },
    async nextStep1() {
      if (!this.form1.email) {
        this.emailError = 'Email is required.';
        return;
      }
      if (this.form1.authCode.length !== 6) {
        this.authCodeError = 'Verification code must be 6 digits.';
        return;
      }
      try {
        const response = await fetch('http://8.219.49.219:8080/onlineShopping/user/verifyCode', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            email: this.form1.email,
            code: this.form1.authCode,
          }),
          credentials: 'include',
        });
        const data = await response.json();
        if (data.data === '验证码正确' && data.code === 200) {
          this.step = 2;
        } else {
          this.authCodeError = 'Verification code is incorrect.';
        }
      } catch (error) {
        this.authCodeError = 'Verification code request failed.';
      }
    },
    nextStep2() {
      if (this.form2.password !== this.form2.confirmPassword) {
        this.passwordMismatch = true;
        return;
      }
      this.step = 3;
      axios.post('http://8.219.49.219:8080/onlineShopping/user/resetPassword', {
        email: this.form1.email,
        password: this.form2.password
        //code: this.form1.authCode,
      })
      .then(response => {
        console.log(response);
      })
      .catch(error => {
        Swal.fire({
          icon: 'error',
          title: '错误',
          text: '重置密码失败.',
        });
      });
    },
    login() {
      this.$router.push({ path: '/login' });
    },
  },
};
</script>

<style scoped>
.password-reset-container {
  max-width: 400px;
  margin: auto;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(3, 141, 72, 0.1);
  background-color: #f9f9f9;
  background-image: url('/pictures/bg.jpg'); 
  background-size: cover; 
  background-repeat: no-repeat;
}

.step {
  margin-bottom: 20px;
}

h2 {
  margin-bottom: 20px;
  color: #333;
}

form {
  display: flex;
  flex-direction: column;
}

label {
  margin-top: 10px;
  font-weight: 500;
  color: #333;
}

input {
  padding: 8px;
  margin-top: 5px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

button {
  margin-top: 10px;
  padding: 10px;
  background-color: #4CAF50; 
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #45a049; 
}

button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

p {
  margin-top: 10px;
  text-align: center;
  color: #ff0000;
}
</style>